package com.blb.edufileservice.listener;


import com.alibaba.fastjson.JSON;
import com.blb.edufileservice.service.IPageService;
import com.learn.eduapi.entity.Course;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;


import static com.blb.edufileservice.config.RabbitMQConfig.*;


@Slf4j
@Component
public class CourseMQListener {

    @Autowired
    private IPageService pageService;

    /**
     * 监听课程添加操作
     */
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = QUEUE_FILE_SAVE, durable = "true"),
                    exchange = @Exchange(value = COURSE_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    , key = KEY_COURSE_SAVE)})
    public void receiveCourseSaveMessage(String json, Channel channel, Message message) throws IOException {
        Course course = JSON.parseObject(json, Course.class);
        log.info("开始创建课程页面：{}" , course );
        pageService.createCoursePage(course.getId());
    }

    /**
     * 监听课程删除操作
     */
    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = QUEUE_FILE_DELETE, durable = "true"),
                    exchange = @Exchange(value = COURSE_EXCHANGE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true")
                    , key = KEY_COURSE_REMOVE)})
    public void receiveCourseDeleteMessage(Long id) {
        log.info("开始删除课程页面：{}",id);
        pageService.deleteCoursePage(id.intValue());
    }
}
